package com.example.netty;

import com.example.netty.handler.NettyServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HelloServer {

    public static void main(String[] args) {
        // 接收客户端连接的线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // 处理读写请求的线程组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 服务器端启动器，组装netty组件
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    // BossEventLoop，处理accept事件
                    // WorkerEventLoop(selector, thread，利用多线程，一个selector配一个thread)，处理read事件
                    .group(bossGroup, workerGroup)
                    // 服务器ServerSocketChannel的实现类
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列中等待连接的个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // boss处理连接，worker（child）负责读写
                    .childHandler(new NettyServerChannelInitializer());
            log.info("服务端准备好了");

            // 同步方式绑定服务监听端口
            ChannelFuture channelFuture = serverBootstrap.bind(9010).sync();
            log.info("服务端已启动");

            // 使用监听器方式优雅退出，释放main线程
            channelFuture.channel().closeFuture().addListener((ChannelFutureListener) future -> {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                log.info("服务端channel已关闭：{}", future.channel());
            });
        } catch (InterruptedException e) {
            bossGroup.shutdownGracefully().syncUninterruptibly();
            workerGroup.shutdownGracefully().syncUninterruptibly();
            log.info("关闭 Netty 成功");
        }
    }
}
